#!/bin/bash
# REQUEST_FOR_LOG_TYPE_ARRAY=("Notification" "Pgyer")
# sh ${CommonFun_HomeDir_Absolute}/brances_info/brances_info_log/get_current_branch_log.sh -envInfoF "${Package_Environment_FILE_PATH}" --request-for-log-types "${REQUEST_FOR_LOG_TYPE_ARRAY[*]}" -comScriptHomeDir "${CommonFun_HomeDir_Absolute}" -resultSaveToJsonF "${TEST_DATA_RESULT_FILE_PATH}"
JQ_EXEC=`which jq`


exit_script() { # 退出脚本的方法，省去当某个步骤失败后，还去继续多余的执行其他操作
    exit 1
}


# 定义颜色常量
NC='\033[0m' # No Color
RED='\033[31m'
GREEN='\033[32m'
YELLOW='\033[33m'
BLUE='\033[34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'

# 当前【shell脚本】的工作目录
# $PWD代表获取当前路径，当cd后，$PWD也会跟着更新到新的cd路径。这个和在终端操作是一样的道理的
CurrentDIR_Script_Absolute="$( cd "$( dirname "$0" )" && pwd )"
#echo "CurrentDIR_Script_Absolute=${CurrentDIR_Script_Absolute}"
#CommonFun_HomeDir_Absolute=${CurrentDIR_Script_Absolute}/..
CommonFun_HomeDir_Absolute2=${CurrentDIR_Script_Absolute%/*} # 使用此方法可以避免路径上有..
CommonFun_HomeDir_Absolute=${CommonFun_HomeDir_Absolute2%/*} # 使用此方法可以避免路径上有..
# CommonFun_HomeDir_Absolute=${CurrentDIR_Script_Absolute}
# echo "CommonFun_HomeDir_Absolute=${CommonFun_HomeDir_Absolute} ✅"

qscript_path_get_filepath="${CommonFun_HomeDir_Absolute}/qscript_path_get.sh"
qbase_update_json_file_singleString_script_path="$(sh ${qscript_path_get_filepath} qbase update_json_file_singleString)"
qbase_function_log_msg_script_path="$(sh ${qscript_path_get_filepath} qbase function_log_msg)"
source $qbase_function_log_msg_script_path # 为了使用 logResultValueToJsonFile 、 logResultValueToJsonFile


get_branch_all_detail_info_script_path="$(sh ${qscript_path_get_filepath} qbase get20_branchMapsInfo_byHisJsonFile)"




function logSuccessMsg() {
    printf "${GREEN}$1${GREEN}\n${NC}"
}

function logMsg() {
    printf "$1\n${NC}"
}

function debug_log() {
    # if [ "${isRelease}" == true ]; then
        echo "$1"
    # fi
}




# 获取当前包所含的功能分支信息
while [ -n "$1" ]
do
    case "$1" in
        -devBranchsJsonF|--devBranchs-json-file) Develop_Branchs_FILE_PATH=$2; shift 2;;
#            -ignoreBranchNames|--ignoreBranchNameArray) ignoreBranchNameArray=$2; shift 2;;
        -branchLogFor|--branchLogFor) branchLogFor=$2; shift 2;;  # Notification / Pgyer
        -pn|--package-default-network) PackageNetworkType=$2; shift 2;;
        -shouldMD|--should-markdown) shouldMarkdownCurrent=$2; shift 2;;
        -resultSaveToJsonF|--result-save-to-json-file-path) RESULT_SALE_TO_JSON_FILE_PATH=$2; shift 2;; # 为简化换行符的保真(而不是显示成换行,导致后面计算数组个数麻烦),将结果保存在的JSON文件
        --) break ;;
        *) echo $1,$2; break ;;
    esac
done


if [ ! -f "${Develop_Branchs_FILE_PATH}" ]; then
    echo "❌Error: 您之前保存本次打包的当前所含的分支信息的Develop_Branchs_FILE_PATH=${Develop_Branchs_FILE_PATH} 中未设置或不存在，请先检查设置"
    exit 1
fi

if [ ! -f "${RESULT_SALE_TO_JSON_FILE_PATH}" ]; then
    echo "❌Error: 您即将用来保存本次打包的当前分支信息结果的文件RESULT_SALE_TO_JSON_FILE_PATH=${RESULT_SALE_TO_JSON_FILE_PATH} 中未设置或不存在，请先检查设置"
    exit 1
fi

if [ -z "${PackageNetworkType}" ]; then
    echo "❌Error:您未设置 -pn|--package-default-network,请先检查设置"
    exit 1
fi

if [ "${branchLogFor}" == "Notification" ]; then
    echo "💡 正获取显示在到【企业微信】上的【本次打包】信息"
    showBranchLogFlag='true'
    showBranchName='true'
    showBranchTimeLog='all'
    showBranchAtLog='true'
    showBranchTable='false' # 通知也暂时都不显示
    showCategoryName='true' # 通知时候显示
elif [ "${branchLogFor}" == "Pgyer" ]; then
    echo "💡 正获取显示在到【蒲公英】上的【本次打包】信息"
    if [ "${PackageNetworkType}" == "product" ]; then
        showBranchLogFlag='false'
        showBranchName='false'
        showBranchTimeLog='none'
        showBranchAtLog='false'
        showBranchTable='false'
        showCategoryName='false' # 更新信息上，如果是生产环境，分支类别暂不显示，其他环境显示
    else
        showBranchLogFlag='true'    # 对更新信息的显示,flag只有在"非生产"环境下才显示
        showBranchName='false'
        showBranchTimeLog='none'
        showBranchAtLog='true'
        showBranchTable='false'
        showCategoryName='true' # 更新信息上，如果是生产环境，分支类别暂不显示，其他环境显示
    fi
else
    echo "❌Error: $FUNCNAME 获取当前分支信息的日志类型入参错误:${branchLogFor}，请检查"
    exit 1
fi

currentBranchLogStringResult=""
Escape_CURRENT_ARRAY_STRING=""

currentHeaderString="当前包新增功能分支信息如下(相比线上包,而不是上个打出的包)："
currentBranchLogStringResult+="${currentHeaderString}"
Escape_CURRENT_ARRAY_STRING+="\"${currentHeaderString}\""

buildContainBranchMaps=$(cat ${Develop_Branchs_FILE_PATH} | ${JQ_EXEC} -r '.package_merger_branchs') # -r 去除字符串引号
# echo "✅✅✅✅✅✅ 4: ${buildContainBranchMaps}"
# exit 1

RESULT_FULL_CURRENT_STRING_SALE_BY_KEY="branch_info_result.${branchLogFor}.current.full"
if [ -z "${buildContainBranchMaps}" ] || [ "${buildContainBranchMaps}" == "null" ]; then
    echo "⚠️友情提示：您的${Develop_Branchs_FILE_PATH}文件中不存在已合如的package_merger_branchs数据"
    EMPTY_FULL_CURRENT_STRING="warning: no any current branchs info"
    currentBranchLogStringResult+=${EMPTY_FULL_CURRENT_STRING}
    Escape_CURRENT_ARRAY_STRING+=",\"${EMPTY_FULL_CURRENT_STRING}\""
    updateBranchResultFileKeyValue "${RESULT_SALE_TO_JSON_FILE_PATH}" "${RESULT_FULL_CURRENT_STRING_SALE_BY_KEY}" "${EMPTY_FULL_CURRENT_STRING}"
else
    # debug_log "正在引入方法文件(为了使用 getAllBranchLogString)：source ${branchs_info_log_common_file_Absolute} -commonFunHomeDir \"${bulidScriptCommon_dir_Absolute}\" --branch-info-json-file \"${Develop_Branchs_FILE_PATH}\""
    # source ${branchs_info_log_common_file_Absolute} -commonFunHomeDir "${bulidScriptCommon_dir_Absolute}" --branch-info-json-file "${Develop_Branchs_FILE_PATH}"
    
    RESULT_BRANCH_ARRAY_SALE_BY_KEY="branch_info_result.${branchLogFor}.current.branch"
    RESULT_CATEGORY_ARRAY_SALE_BY_KEY="branch_info_result.${branchLogFor}.current.category"
    RESULT_FULL_STRING_SALE_BY_KEY="branch_info_result.${branchLogFor}.current.full"
    # debug_log "正在使用引入文件 ${BLUE}${branchs_info_log_common_file_Absolute} ${NC}中的方法(获取当前打包信息):《 ${BLUE}getAllBranchLogString -branchMaps \"${buildContainBranchMaps}\" -showCategoryName \"${showCategoryName}\" -showFlag \"${showBranchLogFlag}\" -showName \"${showBranchName}\" -showTime \"${showBranchTimeLog}\" -showAt \"${showBranchAtLog}\" -showTable \"${showBranchTable}\" -shouldMD \"${shouldMarkdownCurrent}\" -resultSaveToJsonF \"${RESULT_SALE_TO_JSON_FILE_PATH}\" -resultBranchKey \"${RESULT_BRANCH_ARRAY_CURRENT_SALE_BY_KEY}\" -resultCategoryKey \"${RESULT_CATEGORY_ARRAY_CURRENT_SALE_BY_KEY}\" -resultFullKey \"${RESULT_FULL_CURRENT_STRING_SALE_BY_KEY}\" ${NC}》${NC}"
    # getAllBranchLogString -branchMaps "${buildContainBranchMaps}" -showCategoryName "${showCategoryName}" -showFlag "${showBranchLogFlag}" -showName "${showBranchName}" -showTime "${showBranchTimeLog}" -showAt "${showBranchAtLog}" -showTable "${showBranchTable}" -shouldMD "${shouldMarkdownCurrent}" -resultSaveToJsonF "${RESULT_SALE_TO_JSON_FILE_PATH}" -resultBranchKey "${RESULT_BRANCH_ARRAY_CURRENT_SALE_BY_KEY}" -resultCategoryKey "${RESULT_CATEGORY_ARRAY_CURRENT_SALE_BY_KEY}" -resultFullKey "${RESULT_FULL_CURRENT_STRING_SALE_BY_KEY}"
    # debug_log "正在使用引入文件 ${BLUE}${branchs_info_log_common_file_Absolute} ${NC}中的方法(获取当前打包信息):《 ${BLUE}getAllBranchLogString -branchMaps \"${buildContainBranchMaps}\" -showCategoryName \"${showCategoryName}\" -showFlag \"${showBranchLogFlag}\" -showName \"${showBranchName}\" -showTime \"${showBranchTimeLog}\" -showAt \"${showBranchAtLog}\" -showTable \"${showBranchTable}\" -shouldMD \"${shouldMarkdownCurrent}\" -resultSaveToJsonF \"${RESULT_SALE_TO_JSON_FILE_PATH}\" -resultBranchKey \"${RESULT_BRANCH_ARRAY_CURRENT_SALE_BY_KEY}\" -resultCategoryKey \"${RESULT_CATEGORY_ARRAY_CURRENT_SALE_BY_KEY}\" -resultFullKey \"${RESULT_FULL_CURRENT_STRING_SALE_BY_KEY}\" ${NC}》${NC}"
    # getAllBranchLogString -branchMaps "${buildContainBranchMaps}" -showCategoryName "${showCategoryName}" -showFlag "${showBranchLogFlag}" -showName "${showBranchName}" -showTime "${showBranchTimeLog}" -showAt "${showBranchAtLog}" -showTable "${showBranchTable}" -shouldMD "${shouldMarkdownCurrent}" -resultSaveToJsonF "${RESULT_SALE_TO_JSON_FILE_PATH}" -resultBranchKey "${RESULT_BRANCH_ARRAY_CURRENT_SALE_BY_KEY}" -resultCategoryKey "${RESULT_CATEGORY_ARRAY_CURRENT_SALE_BY_KEY}" -resultFullKey "${RESULT_FULL_CURRENT_STRING_SALE_BY_KEY}"
    

    # buildContainBranchMaps="[]"
    debug_log "${YELLOW}正在执行命令(进行分类4):《 ${BLUE}sh $get_branch_all_detail_info_script_path  -branchMapsInJsonF \"${Develop_Branchs_FILE_PATH}\" -branchMapsInKey \".package_merger_branchs\" -showCategoryName \"${showCategoryName}\" -showFlag \"${showBranchLogFlag}\" -showName \"${showBranchName}\" -showTime \"${showBranchTimeLog}\" -showAt \"${showBranchAtLog}\" -showTable \"${showBranchTable}\" -shouldMD \"${shouldMarkdownCurrent}\" -resultSaveToJsonF \"${RESULT_SALE_TO_JSON_FILE_PATH}\" -resultBranchKey \"${RESULT_BRANCH_ARRAY_SALE_BY_KEY}\" -resultCategoryKey \"${RESULT_CATEGORY_ARRAY_SALE_BY_KEY}\" -resultFullKey \"${RESULT_FULL_STRING_SALE_BY_KEY}\" ${YELLOW}》${NC}"
    sh $get_branch_all_detail_info_script_path -branchMapsInJsonF "${Develop_Branchs_FILE_PATH}" -branchMapsInKey ".package_merger_branchs" -showCategoryName "${showCategoryName}" -showFlag "${showBranchLogFlag}" -showName "${showBranchName}" -showTime "${showBranchTimeLog}" -showAt "${showBranchAtLog}" -showTable "${showBranchTable}" -shouldMD "${shouldMarkdownCurrent}" -resultSaveToJsonF "${RESULT_SALE_TO_JSON_FILE_PATH}" -resultBranchKey "${RESULT_BRANCH_ARRAY_SALE_BY_KEY}" -resultCategoryKey "${RESULT_CATEGORY_ARRAY_SALE_BY_KEY}" -resultFullKey "${RESULT_FULL_STRING_SALE_BY_KEY}"
    if [ $? != 0 ]; then
        echo "$FUNCNAME ❌Error:获取所有分支的Log信息，并保存到指定文件中！"
        exit 1
    fi


    currentBranchLogStringResult+="\n${LAST_BRANCHS_INFO_STRING}"

    Escape_LAST_BRANCH_ARRAY_ONLY_STRING_noDoubleQuote=${Escape_LAST_BRANCH_ARRAY_ONLY_STRING: 1:${#Escape_LAST_BRANCH_ARRAY_ONLY_STRING}-2} # 去掉前后的双引号，再去做数据的更改
    Escape_CURRENT_ARRAY_STRING+=",\"${Escape_LAST_BRANCH_ARRAY_ONLY_STRING_noDoubleQuote}\""
fi

# 去除最后一个字符,即逗号"," (当开头一定有值的时候，我们在加字符串的时候，可以选择在前面加逗号，这样就不用在尾部去除了。但是一定得开头有值)
# if [ -n "${Escape_CURRENT_ARRAY_STRING}" ] && [ "${Escape_CURRENT_ARRAY_STRING}" != "[" ]; then
#     Escape_CURRENT_ARRAY_STRING=${Escape_CURRENT_ARRAY_STRING: 0:${#Escape_CURRENT_ARRAY_STRING}-2}
# fi

#    echo "============当前打包信息currentBranchLogStringResult(${branchLogFor})============\n${currentBranchLogStringResult}"